﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using QSAspMvc.Data;
using QSAspMvc.Models;
using ValidationFramework.Web.MVC;

namespace QSAspMvc.Controllers
{
	public class ProductController : Controller
	{
		private readonly IProductRepository productRepository;
		public ProductController()
		{
			productRepository = new SessionProductRepository();
		}

		//
		// Browse Action
		// 
		// URL:  /Products/Browse
		//
		public object Browse()
		{
			var products = productRepository.GetProducts().ToList();

			return View(products);
		}


		//
		// Create Action
		// 
		// URL:  /Products/Create
		//

		[AcceptVerbs("GET")]
		public object Create()
		{
			return View(new Product());
		}

		[AcceptVerbs("POST")]
		public object Create(Product product)
		{
			// redisplay form immediately if there are input format errors
			if (!ViewData.ModelState.IsValid)
			{
				return View(product);
			}

			// validate model and bind errors to modelState
			ModelStateBinder.UpdateModelState(product, ViewData.ModelState);

			// redisplay if there are model state errors
			if (!ViewData.ModelState.IsValid)
			{
				ViewData["Message"] = "Oops: Error";
				return View(product);
			}

			productRepository.SaveProduct(product);
			return RedirectToAction("Browse");
		}

		[AcceptVerbs("GET")]
		public object CreateAdvanced()
		{
			return View(new Product());
		}

		[AcceptVerbs("POST")]
		public object CreateAdvanced(Product product)
		{
			// redisplay form immediately if there are input format errors
			if (!ViewData.ModelState.IsValid)
			{
				return View(product);
			}

			// validate model and bind errors to modelState
			ModelStateBinder.UpdateModelState(product, ViewData.ModelState);

			// redisplay if there are model state errors
			if (!ViewData.ModelState.IsValid)
			{
				ViewData["Message"] = "Oops: Error";
				return View(product);
			}

			productRepository.SaveProduct(product);
			return RedirectToAction("Browse");
		}
	}
}
